var DeviceModule = require('./DeviceModule.js');
"ui";
ui.layout(
    <vertical padding="16">
        <button id="btnTest" text="test" />
        <button id="btnChangeDevice" text="变换设备" />
        <button id="btnLaunch" text="启动包"/>
    </vertical>
);

// 创建一个事件监听器，等待子线程传递数据
events.observeKey();
events.on("data_received", function(data) {
    log("主线程收到数据: " , data);
});

ui.btnTest.click(()=>{
    try {
        DeviceModule.test();
    } catch (error) {
        console.log('error = ' , error);
    }
});

ui.btnChangeDevice.click(()=>{
    threads.start(function() {
        // 向服务器发送http请求
        var url = "http://192.168.0.109:9527/RandomDevice";
        try {
            let r = http.postJson(url,{});
            // console.log('RandomDevice r = ' , r.body.json());
            events.emit("data_received", r.body.json());
        } catch (error) {
            console.log('error = ' , error);
        }
    });
});

ui.btnLaunch.click(function(){
    app.launch('com.anode.sortnuts');
    // setTimeout();
    // auto.waitFor();
    // var sendButton = text("发送").findOne();
    // sendButton.click();
    setTimeout(()=>{
        try {
            console.log('--------timeout');
            // var sendButton = text("Syn AutoJS").findOne();
            // if(sendButton){
            //     console.log('-------autojs clicked');
            //     sendButton.click();
            // }else{
            //     console.log('-------can not find');
            // }
            
        } catch (error) {
            console.log('------error = ' , error);
        }
        
    },5000)
});

function registUser(strI50,strMediate,strDevice){
    var url = "http://192.168.0.109:9527/RegistUser";
    try {
        let r = http.postJson(url, {
            i50 : strI50,
            deviceInfo : strDevice,
            mediate : strMediate
        });
        console.log('registUser r = ' , r);
    } catch (error) {
        console.log('error = ' , error);
    }
}

function startDeviceInfoService(){
    var receiver = new android.content.BroadcastReceiver({
        onReceive: function(context, intent) {
            var strI50 = intent.getStringExtra("i50");
            var strMediate = intent.getStringExtra("mediate");
            var strDevice = intent.getStringExtra("device");
            log("Received message: strI50 = " + strI50);
            threads.start(function() {
                registUser(strI50,strMediate,strDevice);
            });
        }
    });
    
    var filter = new android.content.IntentFilter("SYN_AUTOHJS");
    context.registerReceiver(receiver, filter);
}

function update(){
    // console.log('111111111');
}

let intervalSecs = 1;
setInterval(() => {
    update();
}, intervalSecs * 1000);

startDeviceInfoService();